#ifndef CANIF_H
#define CANIF_H

#include <QObject>
#include <QQueue>
#include <QThread>
#include <QVector>
#include "stdint.h"
#include <QMetaType>
#include "candriver.h"

class CanIF;

class VPort : public QObject
{
    Q_OBJECT
public:
    VPort(CanIF *pDev);
public:
    bool Transmit(const sCANObj &canmsg);
    bool MsgIn(const sCANObj &msg);

    bool Receive(sCANObj *canmsg,int WaitTime=-1);
    bool Mask(uint32_t uId);
    bool SetMask(uint32_t uMask,uint32_t uAck){
        this->uMask = uMask;
        this->uAck = uAck;
        return true;
    };
    bool ClearBuffer();
    HANDLE hRxEvent;
private:
    uint32_t uMask = 0xFFFFFFFF;
    uint32_t uAck = 0x00000000;
    QQueue<sCANObj> mRxBuf;
    QMutex mutex;
    CanIF *pDevice;
};

class CanIF : public QThread
{
    Q_OBJECT
public:
    CanIF();
    ~CanIF();

    bool OpenDevice(QString sMakers,QString sDevName,const sCanBaud mBaud);
    bool CloseDevice();

    VPort *CreateVPort(uint32_t Ack,uint32_t Mask);
    bool DelVPort(VPort *pPort);
    bool PortRead(VPort *pPort,const sCANObj &msg,int WaitTime=-1);
    virtual void Send(const sCANObj &msg);

    int GetSta(void){
        if(pCanDrv == 0)
            return 0;

        if(pCanDrv->GetSta() != 0){
            return 3;
        };

        if(bRun)
            return 1;
        else
            return 2;
    }

signals:
    void receive(const sCANObj &msg); // 用于向主线程发送数据的信号函数， 在.cpp中，没有进行定义，直接使用emit进行数据的发送
    void updateLabelText(sCANObj msg);
protected:
    uint32_t uCh;
private:
    uint32_t uAck;
    uint32_t uMask;
    QVector<VPort*> portArray;
    CanDriver *pCanDrv = 0;
    bool bRun = false;
public:
    uint32_t uTxCnt = 0;
    uint32_t uRxCnt = 0;
    SYSTEMTIME startTime;
    uint64_t uStartTimeStamp;
    void run();
    void ResetTimeStamp();
};

#endif // CANIF_H
